package finance


import org.apache.commons.math.stat.StatUtils

class MovingAverageService {

    static transactional = true

    def sma(list, period) {
      def averages = []

      for( i in (period - 1)..<list.size()) {
         def sublist = list[i..< Math.min(period + i, list.size() )]
         averages << StatUtils.mean(sublist as double[])
      }

      return averages
    }

    def wma(vals, period) {    
        def averages = [] 
        
	    for( i in (period - 1)..<vals.size()) {
	        def sublist = vals[i..< Math.min(period + i, vals.size() )]
	        averages << weightedMean(sublist as double[])
	    }
        
        return averages
    }
    
    def weightedMean(vals) {
        def total = 0.0
        def weightsSum = 0.0

        for(i in 0..<vals.size()) {
            if(vals[i] == null) vals[i] = 0.0
            
            total += i * vals[i] 
            weightsSum += i
        }
        
        return total/weightsSum
    }
}
